var ns, UIAlbumBrowser, bmLocation,imageHandle;
app = new Vue({
    el: '#app',
    data: {
        form: {
            pageindex: 0,
            pagesize: 10,
            // status: 1, // 1-任务列表 2-新增记录
            PlanType: 1,
            TaskStatus:0//0-未开始,1-进行中,2-已结束

        },
        newform: {
            PlanType: 1,
            EncriptID: '',
            DeviceID: 0,
            DeviceName: '',
            DeviceLocationPlace:'',
            DeviceNo: '',
            ModelNo:'',
            ProjectID: 0,
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            ProcessContent: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: '',
            IsAllowUpload: false
        },
        standardlist: [],
        imglist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,
        ProjectList: [],
        projectSelected:0,
        maxuploadcount: CONFIG.maxuploadcount,
    },
    methods: {
        do_choose_device: function() {
            var that = this;
            ns.openWin('equipment_devicelist_frm', '选择设备', {
                projectid: that.newform.ProjectID

            });
        },
        do_save: function() {
            var that = this;
            if (that.newform.DeviceID <= 0) {
                api.toast({
                    msg: '请选择设备',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CheckStatus == 2) { //异常
                api.confirm({
                    title: '提示',
                    msg: '当前结果异常,是否需要进行报事报修登记?',
                    buttons: ['报事报修', '直接完成']
                }, function(ret, err) {
                    var ServiceStatus = -1;
                    if (ret.buttonIndex == 1) {
                        ServiceStatus = 1;
                    } else if (ret.buttonIndex == 2) {
                        ServiceStatus = 0;
                    }
                    if (ServiceStatus >= 0) {
                        that.do_save_process(ServiceStatus);
                    }
                });
                return;
            }
            that.do_save_process(0);
        },
        do_save_process: function(ServiceStatus) {
            var that = this;
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.DeviceID = that.newform.DeviceID;
            options.PlanType = that.newform.PlanType;
            options.standardlist = JSON.stringify(that.standardlist);
            options.CheckStatus = that.newform.CheckStatus;
            options.GPSLocation = that.newform.GPSLocation;
            options.ServiceStatus = ServiceStatus;
            options.TaskCompleteContent = that.newform.TaskCompleteContent;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    //api.sendEvent({
                    //    name: 'devicetaskcomplete',
                    //});
                    setTimeout(function() {
                        api.closeWin();
                    }, 500)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        select_active: function(item, CheckStatus) {
            var that = this;
            item.CheckStatus = CheckStatus;
            var isallnormal = true;
            for (var i = 0; i < that.standardlist.length; i++) {
                if (that.standardlist[i].CheckStatus == 2) {
                    isallnormal = false;
                }
            }
            if (isallnormal) {
                this.newform.CheckStatus = 1;
            } else {
                this.newform.CheckStatus = 2;
            }
        },
        select_all_active: function(CheckStatus) {
            var that = this;
            that.newform.CheckStatus = CheckStatus;
            // for (var i = 0; i < that.standardlist.length; i++) {
            //     that.standardlist[i].CheckStatus = CheckStatus;
            // }
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                // that.upload_choose_picture();
                that.choose_picture_start();
            })
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'url',
                allowEdit: false,
                quality: 100,
                saveToPhotoAlbum: false,
                targetWidth: 1750,
                targetHeight: 1800,
            }, function(ret, err) {
                if (ret) {
                    // alert(JSON.stringify(ret));
                    that.imageHandle_transPath(ret.data);
                         
                } else {
                    alert(JSON.stringify(err));
                }
            });
        },
         //加时间水印
        imageHandle_transPath: function (imagePath) {
            var that = this;
            var nowdate = ns.DealTimeYYMMDDHHSS(new Date);
            imageHandle.setText({
                path: imagePath,
                text: '拍摄时间:'+nowdate,
                textPoint: {
                    x: 100,   //（可选项）数字类型；文字水印x坐标；默认：50
                    y: 1600,   //（可选项）数字类型；文字水印y坐标；默认：50
                },
                textColor: '#ffffff',
                textFont: 60,
            }, function (ret) {
                if (ret.status) {
                    that.imageHandle_transPathAddress(ret.path);
                }
            });
        },
        //加地点水印
        imageHandle_transPathAddress:function(imagePath){
            var that = this;
            if(that.newform.GPSLocation){
                imageHandle.setText({
                    path: imagePath,
                    text:'拍摄地点:'+ that.newform.GPSLocation,
                    textPoint: {
                        x: 100,   //（可选项）数字类型；文字水印x坐标；默认：50
                        y: 1500,   //（可选项）数字类型；文字水印y坐标；默认：50
                    },
                    textColor: '#ffffff',
                    textFont:60,
                }, function (ret) {
                    // alert(JSON.stringify(ret));
                    if (ret.status) {
                        that.FNPhotograph_transPath(ret.path);
                    }
                });
            } 
            else{
                that.FNPhotograph_transPath(imagePath);
            }
        }, 
        
        //给imglist 添加数据
        FNPhotograph_transPath:function(imagePath){
            var that = this;
            that.imglist.push({
                ID: 0,
                index: that.imgindex,
                url: imagePath,
                thumbPath: imagePath,
                isupload: true
            });
            that.imgindex++;         
        },
        choose_picture_start: function() {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function(ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        UIAlbumBrowser_transPath: function() {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function(ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        remove_img: function(index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                    if (item.ID > 0) {
                        that.do_remove_uploadimg(item);
                    }
                }
            }
        },
        do_remove_uploadimg: function(item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function(succeed, data, err) {});
        },
        StartBmap: function() {
            var that = this;
            ns.confirmPer('location', function() {
                that.StartLocation();
            })
        },
        StartLocation: function() {
            var that = this;
            var num = 0; //次数
            that.newform.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function(ret) {
                if (ret.status) {
                    that.newform.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber;
                }
            });
        },
        configManager: function() {
            bmLocation.configManager({
                accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
        do_viewimages: function(activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        get_standard_data: function() {
            var that = this;
            if (that.newform.DeviceID <= 0 && that.newform.EncriptID == '') {
                return;
            }
            var options = {};
            options.action = "getdevicestandardlist";
            options.DeviceID = that.newform.DeviceID;
            options.EncriptID = that.newform.EncriptID;
            options.PlanType = that.newform.PlanType;
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.standardlist = data.list;
                    that.newform.CheckTime = data.CheckTime;
                    that.newform.InChargeManName = data.InChargeManName;
                    if (that.newform.EncriptID != '') {
                        that.newform.DeviceID = data.DeviceID;
                        that.newform.DeviceName = data.DeviceName;
                        that.newform.ProjectID = data.ProjectID;
                        that.newform.ProjectName = data.ProjectName;
                        that.newform.DeviceNo = data.DeviceNo;
                        that.newform.ModelNo = data.ModelNo;
                        that.newform.DeviceLocationPlace = data.DeviceLocationPlace;
                    }
                    that.newform.EncriptID = '';
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_select_plantype: function(type) {
            this.newform.PlanType = type;
            this.get_standard_data();
        },
        do_choose_project: function() {
            var that = this;
            ns.openWin('chooseprojectlist_frm', '选择项目', {
                projectlevel: 1,
            });
        },
        get_select_project: function(data) {
            var that = this;
            that.newform.ProjectID = data.projectid;
            that.newform.ProjectName = data.name;
        },
        get_project_list: function() {
            var that = this;
            var options = {
                action: 'getmytopprojectlist'
            };
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    that.newform.ProjectID = that.ProjectList[0].ID;
                    that.newform.ProjectName = that.ProjectList[0].Name;
                    that.initPicker();//加载下拉列表数据
                }
            });
        },
        do_selectProject:function(){
            var that=this;
            that.newform.DeviceName='';
            that.newform.DeviceNo='';
            that.newform.ModelNo='';
            that.newform.DeviceLocationPlace='';
        },   
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    // 选择项目
                    var pickerProject = new $.PopPicker({
                        layer: 1,
                        fileID: 'ID',
                        fileName: 'Name',
                    });
                    var projectData = _this.ProjectList || [];
                    pickerProject.setData(projectData);
                    var showProjectPickerButton = doc.getElementById('chooseproject');
                    showProjectPickerButton.addEventListener('click', function (event) {
                        pickerProject.show(function (items) {
                            if(_this.newform.ProjectID!= items[0].value){    
                                _this.newform.DeviceID = 0;
                                _this.newform.DeviceName = '';
                                _this.newform.IsAllowUpload = false;
                                _this.newform.DeviceNo= '';
                                _this.newform.ModelNo= '';
                                _this.newform.DeviceLocationPlace= '';
                                _this.standardlist =[];
                            }
                            _this.newform.ProjectID = items[0].value;
                            _this.newform.ProjectName = items[0].text;
                            //返回 false 可以阻止选择框的关闭
                            //return false;
                        });
                    }, false);
                });
            })(mui, document);
        },
    },
    
});
apiready = function() {
    api.parseTapmode();
    ns = window.Foresight.Util;
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    bmLocation = api.require('bmLocation');
    imageHandle = api.require('imageHandle');

    app.newform.EncriptID = api.pageParam.EncriptID || '';
    app.get_project_list();
    setTimeout(function() {
        if (app.newform.EncriptID != '') {
            app.get_standard_data();
        } 
    }, 500)
    setTimeout(function() {
        app.configManager();
        app.StartBmap();
    }, 1000)
    api.addEventListener({
        name: 'do_choose_device_done'
    }, function(ret, err) {
        app.newform.DeviceID = ret.value.id;
        app.newform.DeviceName = ret.value.name;
        app.newform.ProjectName = ret.value.projectname;
        app.newform.IsAllowUpload = ret.value.IsAllowUpload;
        app.newform.DeviceNo= ret.value.DeviceNo,
        app.newform.ModelNo= ret.value.ModelNo,
        app.newform.DeviceLocationPlace= ret.value.DeviceLocationPlace,
        app.get_standard_data();
    });
    app.get_select_project(api.pageParam);
    api.addEventListener({
        name: 'do_choose_project_complete'
    }, function(ret) {
        app.get_select_project(ret.value);
    })
};

